﻿<%@ WebHandler Language="C#" Class="AutoStartContainerHandler" %>

/*Description: 自动开卡处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20231201
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Collections;
using NPOI.SS.UserModel;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;

public class AutoStartContainerHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    string fileBasePath = System.Configuration.ConfigurationManager.AppSettings["ImportPath"].ToString();//导入临时路径
    private AutoStartContainerBusiness autoStartBusiness = new AutoStartContainerBusiness();
    string ruleOperaType = "AutoStartRule";

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                /*----------------开卡规则-------------------*/
                case "GetContainerStartRuleData": //获取自动开卡规则维护数据
                    GetContainerStartRuleData(context);
                    break;
                case "GetContainerStartRuleDetailInfo": //获取自动开卡规则维护明细
                    GetContainerStartRuleDetailInfo(context);
                    break;
                case "InitAutoStartRuleDialogData": //初始化自动开卡规则维护弹窗页面
                    InitAutoStartRuleDialogData(context);
                    break;
                case "GetProductAndWorkFlowInfo": //获取件号默认信息以及工艺默认信息
                    GetProductAndWorkFlowInfo(context);
                    break;
                case "SaveContainerAutoStartRuleData": //保存自动开卡规则数据
                    SaveContainerAutoStartRuleData(context);
                    break;
                case "ImportAutoStartRule": //自动开卡规则数据导入
                    ImportAutoStartRule(context);
                    break;
                case "ExportAutoStartRuleToExcel": //自动开卡规则数据导出
                    ExportAutoStartRuleToExcel(context);
                    break;
                /*----------------一键开卡-------------------*/
                case "GetNotStartContainerInfo": //获取未开卡的订单数据
                    GetNotStartContainerOrderInfo(context);
                    break;
                case "GetContainerErrorInfo": //获取开卡出错日志
                    GetContainerErrorInfo(context);
                    break;
                case "GetContainerMakeingInfo": //获取在制开卡数据
                    GetContainerMakeingInfo(context);
                    break;
                case "OneKeyStartContainerInfo": //一键开卡
                    OneKeyStartContainerInfo(context);
                    break;
                case "ExportErrorInfoToExcel": //导出批次开卡异常记录
                    ExportErrorInfoToExcel(context);
                    break;
                case "ExportTaskContainerToExcel": //导出定时任务已开卡数据
                    ExportTaskContainerToExcel(context);
                    break;
                /*----------------批次型别-------------------*/
                case "GetContainerProductFamilyList": //获取批次型别列表
                    GetContainerProductFamilyList(context);
                    break;
                case "InitProductFamilyDialogData": //初始化批次型别修改
                    InitProductFamilyDialogData(context);
                    break;
                case "GetProductFamilyData": //通过型别类型获取机型数据
                    GetProductFamilyData(context);
                    break;
                case "SaveContainerProductFamily": //保存机型数据
                    SaveContainerProductFamily(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未知功能" }));
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 导出自动开卡规则数据
    /// </summary>
    /// <param name="context"></param>
    public void ExportAutoStartRuleToExcel(HttpContext context)
    {
        StringBuilder sql = new StringBuilder();
        if (context.Request["status"].ToString() != "1")
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = "导出必须查询启用的数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        sql.AppendLine(@"SELECT ca.productname 件号,wc.workcentername 主制工区,
                        e.fullname 工艺员,DECODE(ca.isselfmfg,0,'是','否') 是否领料,
                        DECODE(ca.containertype,2,'批量加工',3,'批量带子序号',7,'单件单卡','') 批次类型,
                        DECODE(ca.iscutcontainer,1,'是','否') 是否切断件,ca.cutqty 分卡数,ca.cutstartstep 分卡工序
                        FROM containerAutoStartRule ca
                        LEFT JOIN Workcenter wc ON wc.workcenterid = ca.workcenterid
                        LEFT JOIN employee e ON e.employeeid = ca.technologyempid
                        LEFT JOIN employee e1 ON e1.employeeid = ca.createemployeeid ");
        sql.AppendFormat(" WHERE ca.factoryid = '{0}' AND ca.status = 1", m_UserInfo.FactoryID);
        //查询件号
        if (!string.IsNullOrWhiteSpace(context.Request["productName"].ToString()))
        {
            sql.AppendFormat(" AND ca.productname like '%{0}%'", context.Request["productName"].ToString());
        }
        //查询创建人
        if (!string.IsNullOrWhiteSpace(context.Request["createName"].ToString()))
        {
            sql.AppendFormat(" AND (e1.fullname LIKE '%{0}%' OR e1.employeename = '{0}')", context.Request["createName"].ToString());
        }
        //查询工区
        if (!string.IsNullOrWhiteSpace(context.Request["workCenter"].ToString()))
        {
            sql.AppendFormat(" WHERE wc.workcentername = '{0}'", context.Request["workCenter"].ToString());
        }
        //查询工艺员
        if (!string.IsNullOrWhiteSpace(context.Request["technologyName"].ToString()))
        {
            sql.AppendFormat(" AND (e.fullname LIKE '%{0}%' OR e.employeename = '{0}')", context.Request["technologyName"].ToString());
        }
        //查询是否领料
        if (!string.IsNullOrWhiteSpace(context.Request["isSelfMfg"].ToString()))
        {
            sql.AppendFormat(" AND ca.isselfmfg = {0}", context.Request["isSelfMfg"].ToString());
        }
        //查询是否切断件
        if (!string.IsNullOrWhiteSpace(context.Request["isCutContainer"].ToString()))
        {
            sql.AppendFormat(" AND ca.iscutcontainer = {0}", context.Request["isCutContainer"].ToString());
        }
        DataTable dtRes = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        byte[] bytes = uLMS_CommonFunction.DataTableExportToExcel(dtRes);
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AddHeader("fileDownload", "1");
        context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}{1}.xls", context.Server.UrlEncode("自动开卡规则导出记录"), DateTime.Now.ToString("yyyyMMddHHmmssffff")));
        context.Response.AddHeader("Content-Length", bytes.Length.ToString());
        context.Response.AddHeader("Content-Type", "UTF-8");
        context.Response.Charset = "UTF-8";
        context.Response.ContentEncoding = Encoding.UTF8;
        context.Response.BinaryWrite(bytes);
        context.Response.Flush();
        context.Response.Close();
    }

    /// <summary>
    /// 保存批次机型数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveContainerProductFamily(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string modifyReason = context.Request["modifyReason"].ToString();//修改理由
        string familyTypeName = context.Request["familyTypeName"].ToString();//机型类型
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["containerDatas"].ToString());//选择的批次
        DataTable dtProductFamily = JsonConvert.DeserializeObject<DataTable>(context.Request["productFamilyDatas"].ToString());//选择的机型
        if (dtContainer.Rows.Count == 0 || string.IsNullOrWhiteSpace(modifyReason) || dtProductFamily.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "请填写完整数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
        string productFamilyIds = string.Empty;
        string productFamilyNames = string.Empty;
        string containerID = string.Empty;
        string notes = string.Empty;
        ArrayList sqlList = new ArrayList();
        string insertPFSql = "INSERT INTO containerproductfamilylist(fieldid,containerid,productfamilylistid,sequence) VALUES('671090800','{0}','{1}',{2})";
        foreach (DataRow container in dtContainer.Rows)
        {
            containerID = container["ContainerID"].ToString();
            sqlList.Add(string.Format("DELETE containerproductfamilylist cc WHERE cc.containerid = '{0}'", containerID));//删除原本的机型
            for (int i = 0; i < dtProductFamily.Rows.Count; i++)
            {
                productFamilyIds += string.Format("{0},", dtProductFamily.Rows[i]["PRODUCTFAMILYID"].ToString());
                productFamilyNames += string.Format("{0} ", dtProductFamily.Rows[i]["PRODUCTFAMILYNAME"].ToString());
                sqlList.Add(string.Format(insertPFSql, containerID, dtProductFamily.Rows[i]["PRODUCTFAMILYID"].ToString(), i + 1));//插入修改的机型
            }
            productFamilyIds = productFamilyIds.TrimEnd(',');
            productFamilyNames = productFamilyNames.Trim();
            sqlList.Add(string.Format("UPDATE containercurrentinfo c SET c.familylistids = '{0}',c.familylistnames = '{1}' WHERE c.containerid = '{2}'", productFamilyIds, productFamilyNames, containerID));//更新批次总表
            sqlList.Add(string.Format("UPDATE container c SET c.mfgbatch = '型别： {0} |' WHERE c.containerid = '{1}'", productFamilyNames, containerID));//更新批次表
            notes = GetPFModifyNotes(containerID, familyTypeName, productFamilyNames, modifyReason);//生成修改日志
            sqlList.Add(commonBusiness.GetInsertCommonMethodOperaLogSql(containerID, m_UserInfo.EmployeeID, notes, "ContainerFamilyModify"));//插入修改日志
            productFamilyIds = string.Empty;//置为空值
            productFamilyNames = string.Empty;
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        result.Result = true; result.Message = "修改成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取型别修改记录
    /// </summary>
    /// <param name="containerID"></param>
    /// <param name="familyType"></param>
    /// <param name="productFamilyNames"></param>
    /// <param name="reason"></param>
    /// <returns></returns>
    private string GetPFModifyNotes(string containerID, string familyType, string productFamilyNames, string reason)
    {
        string notes = string.Empty;
        string sql = string.Format(@"SELECT c.familylistnames,c.familylistids FROM containercurrentinfo c WHERE c.containerid = '{0}'", containerID);
        DataTable dtContainer = DatabaseHelper.Query_ReturnDatTable(sql);
        if (string.IsNullOrWhiteSpace(dtContainer.Rows[0]["familylistids"].ToString()))
        {
            notes = string.Format("型别类型由 空值 改为：{0}；型别由 空值 改为：{1}；", familyType, productFamilyNames);
        }
        else
        {
            string[] listIds = dtContainer.Rows[0]["familylistids"].ToString().Split(',');
            sql = string.Format(@"SELECT decode(pf.familytype,1,'批产',2,'主研',3,'参研',4,'修理') familytypename FROM productfamily pf WHERE pf.productfamilyid = '{0}'", listIds[0]);
            DataTable dtPF = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtPF.Rows.Count == 0)
            {
                notes = string.Format("型别类型由 无效空值 改为：{0}；", familyType);
            }
            else
            {
                if (dtPF.Rows[0]["familytypename"].ToString() != familyType)
                {
                    notes = string.Format("型别类型由 {0} 改为：{1}；", dtPF.Rows[0]["familytypename"].ToString(), familyType);
                }
            }
            if (dtContainer.Rows[0]["familylistnames"].ToString() != productFamilyNames)
            {
                notes += string.Format("机型由 {0} 改为：{1}；", dtContainer.Rows[0]["familylistnames"].ToString(), productFamilyNames);
            }
        }
        notes += string.Format("修改理由：{0}", reason);
        return notes;
    }

    /// <summary>
    /// 初始化机型修改弹窗页面
    /// </summary>
    /// <param name="context"></param>
    public void InitProductFamilyDialogData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string containerID = context.Request["containerID"].ToString();
        string sql = string.Format("SELECT c.productfamilylistid FROM containerproductfamilylist c WHERE c.containerid = '{0}'", containerID);
        DataTable dtProductFamily = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtProductFamily.Rows.Count > 0)
        {
            string productFamilyId = dtProductFamily.Rows[0]["productfamilylistid"].ToString();
            sql = string.Format("SELECT pf.familytype FROM PRODUCTFAMILY pf WHERE pf.productfamilyid = '{0}'", productFamilyId);
            DataTable dtFamilyType = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtFamilyType.Rows.Count > 0)
            {
                result.ReturnData = dtFamilyType.Rows[0]["familytype"].ToString();//返回批次的机型类型
                result.DBTable = dtProductFamily;
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取机型列表
    /// </summary>
    /// <param name="context"></param>
    public void GetProductFamilyData(HttpContext context)
    {
        string familyType = context.Request["familyType"].ToString();
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        result.DBTable = commonBusiness.GetProductFamily(new Dictionary<string, string> { { "FamilyType", familyType } });
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取批次型别列表
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerProductFamilyList(HttpContext context)
    {
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT c.mfgordername,c.productname,c.qty,c.containerid,c.containername,c.familylistnames,c.familylistids 
                            FROM containercurrentinfo c WHERE c.originalfactoryid = '{0}'", m_UserInfo.FactoryID);
        if (!string.IsNullOrWhiteSpace(dic["orderName"]))
        {
            sql.AppendFormat(" AND c.mfgordername like '%{0}%'", dic["orderName"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["productName"]))
        {
            sql.AppendFormat(" AND c.productname like '%{0}%'", dic["productName"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["containerName"]))
        {
            sql.AppendFormat(" AND c.containerName like '%{0}%'", dic["containerName"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["productFamilyName"]))
        {
            sql.AppendFormat(" AND c.familylistnames like '%{0}%'", dic["productFamilyName"]);
        }
        //批次状态
        switch (dic["containerStatus"])
        {
            case "1"://新开卡
                sql.AppendLine(" AND c.containerstatus = 1 AND c.isinstore = -1");
                break;
            case "2"://在制
                sql.AppendLine(" AND c.containerstatus = 1 AND c.isinstore = 0");
                break;
            case "3"://入库
                sql.AppendLine(" AND c.containerstatus = 1 AND c.isinstore = 1");
                break;
            case "4"://已关闭
                sql.AppendLine(" AND c.containerstatus = 2");
                break;
            default:
                break;
        }
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(dic["pageIndex"].ToString());
        pageDto.PageSize = int.Parse(dic["pageSize"].ToString());
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 导出定时任务已开卡数据
    /// </summary>
    /// <param name="context"></param>
    public void ExportTaskContainerToExcel(HttpContext context)
    {
        StringBuilder sql = new StringBuilder();
        sql.AppendLine("SELECT cci.mfgordername \"订单号\",cci.productname \"件号\",cci.containername \"批次号\",");
        sql.AppendLine("cci.workflowname || ':' || cci.workflowrevision \"工艺\", cci.workflowstepname \"工序\",cci.qty \"数量\",");
        sql.AppendLine("DECODE(cci.containertype,'2','批量加工','3','批量带子序号','7','单件单卡') \"批次类型\",cc.originalstartdate \"开卡日期\"");
        sql.AppendFormat(@" FROM containercurrentinfo cci
                            LEFT JOIN container cc ON cc.containerid = cci.containerid
                            LEFT JOIN Userattribute ua ON ua.parentid = cci.containerid AND ua.userattributename = '自动开卡'
                            WHERE cci.containerstatus = 1 AND cci.isinstore <> 1 AND cci.originalfactoryid = '{0}' 
                            AND ua.attributevalue = '自动'", m_UserInfo.FactoryID);

        if (!string.IsNullOrWhiteSpace(context.Request["scanOrderName"].ToString()))
        {
            sql.AppendFormat(" AND cci.mfgordername = '{0}'", context.Request["scanOrderName"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request["productName"].ToString()))
        {
            sql.AppendFormat(" AND cci.productname = '{0}'", context.Request["productName"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request["containerName"].ToString()))
        {
            sql.AppendFormat(" AND cci.containerName = '{0}'", context.Request["containerName"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request["startDate"].ToString()))
        {
            sql.AppendFormat(" AND cci.originalstartdate >= to_date('{0}','YYYY-MM-DD')", context.Request["startDate"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request["endDate"].ToString()))
        {
            sql.AppendFormat(" AND cci.originalstartdate <= to_date('{0}','YYYY-MM-DD')", context.Request["endDate"].ToString());
        }
        sql.AppendLine(" ORDER BY cc.originalstartdate DESC");
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "无数据" }));
            return;
        }
        byte[] bytes = uLMS_CommonFunction.DataTableExportToExcel(dt, "定时任务自动开卡记录");
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AddHeader("fileDownload", "1");
        context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}{1}.xls", context.Server.UrlEncode("定时任务自动开卡记录"), DateTime.Now.ToString("yyyyMMddHHmmssffff")));
        context.Response.AddHeader("Content-Length", bytes.Length.ToString());
        context.Response.AddHeader("Content-Type", "UTF-8");
        context.Response.Charset = "UTF-8";
        context.Response.ContentEncoding = Encoding.UTF8;
        context.Response.BinaryWrite(bytes);
        context.Response.Flush();
        context.Response.Close();
    }

    /// <summary>
    /// 导出批次开卡异常记录
    /// </summary>
    /// <param name="context"></param>
    public void ExportErrorInfoToExcel(HttpContext context)
    {
        string sql = "SELECT ac.mfgordername \"订单号\",ac.productname \"件号\",ac.notes \"异常原因\",ac.createdate \"异常日期\"";
        sql += " FROM AutoStartContainerErrorInfo ac ORDER BY ac.createdate DESC,ac.mfgordername";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "无数据" }));
            return;
        }
        byte[] bytes = uLMS_CommonFunction.DataTableExportToExcel(dt, "自动开卡异常记录");
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AddHeader("fileDownload", "1");
        context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}{1}.xls", context.Server.UrlEncode("自动开卡异常记录"), DateTime.Now.ToString("yyyyMMddHHmmssffff")));
        context.Response.AddHeader("Content-Length", bytes.Length.ToString());
        context.Response.AddHeader("Content-Type", "UTF-8");
        context.Response.Charset = "UTF-8";
        context.Response.ContentEncoding = Encoding.UTF8;
        context.Response.BinaryWrite(bytes);
        context.Response.Flush();
        context.Response.Close();
    }
    /// <summary>
    /// 获取在制开卡数据
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerMakeingInfo(HttpContext context)
    {
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT Row_Number() OVER(ORDER BY cc.originalstartdate DESC) numer,cci.mfgordername,
                                    cci.containername,cci.containerid,cci.workflowname || ':' || cci.workflowrevision workflownameandrev, cci.workflowstepname,
                                    cci.productname,cci.qty,cci.containertype,DECODE(cci.containertype,'2','批量加工','3','批量带子序号','7','单件单卡') containertypename,
                                    cc.originalstartdate createdate,f.factoryname,wct.workcentername,te.teamname
                                    FROM containercurrentinfo cci
                                    LEFT JOIN container cc ON cc.containerid = cci.containerid
                                    LEFT JOIN Userattribute ua ON ua.parentid = cci.containerid AND ua.userattributename = '自动开卡'
                                    LEFT JOIN productteaminfo pti ON pti.productname = cci.productname
                                    LEFT JOIN team te ON te.teamid = pti.teamid
                                    LEFT JOIN workcenter wct ON wct.workcenterid = te.workcenterid
                                    LEFT JOIN factory f ON f.factoryid = wct.factoryid
                                    WHERE cci.containerstatus = 1 AND cci.isinstore <> 1 AND cci.originalfactoryid = '{0}' 
                                    AND ua.attributevalue = '{1}'", m_UserInfo.FactoryID, dic["type"]);

        if (!string.IsNullOrWhiteSpace(dic["scanOrderName"]))
        {
            sql.AppendFormat(" AND cci.mfgordername = '{0}'", dic["scanOrderName"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["productName"]))
        {
            sql.AppendFormat(" AND cci.productname = '{0}'", dic["productName"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["containerName"]))
        {
            sql.AppendFormat(" AND cci.containerName = '{0}'", dic["containerName"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["startDate"]))
        {
            sql.AppendFormat(" AND cci.originalstartdate >= to_date('{0}','YYYY-MM-DD')", dic["startDate"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["endDate"]))
        {
            sql.AppendFormat(" AND cci.originalstartdate <= to_date('{0}','YYYY-MM-DD')", dic["endDate"]);
        }

        if (!string.IsNullOrWhiteSpace(dic["ddlFactory"]))
        {
            sql.AppendFormat(" AND f.factoryid = '{0}'", dic["ddlFactory"]);
        }

        if (!string.IsNullOrWhiteSpace(dic["ddlWorkcenter"]))
        {
            sql.AppendFormat(" AND wct.workcenterid = '{0}'", dic["ddlWorkcenter"]);
        }

        //件号主制单元
        if (!string.IsNullOrWhiteSpace(dic["ddlTeam"]))
        {
            sql.AppendFormat(" AND te.teamid = '{0}'", dic["ddlTeam"]);
        }

        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(dic["pageIndex"].ToString());
        pageDto.PageSize = int.Parse(dic["pageSize"].ToString());
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取开卡出错日志
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerErrorInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        dic.Add("FactoryID", m_UserInfo.FactoryID);
        result = autoStartBusiness.GetAutoStartContainerErrorList(dic);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 一键开卡
    /// </summary>
    /// <param name="context"></param>
    public void OneKeyStartContainerInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        AutoStartContainerParam param = JsonConvert.DeserializeObject<AutoStartContainerParam>(context.Request["param"].ToString());
        param.AutoType = "手动";
        result = autoStartBusiness.OneKeyStartContainerInfo(param, m_UserInfo);
        if (!result.Result && result.ReturnData == null)
        {
            autoStartBusiness.CreateAutoStartErrorInfo(GetStartErrorInfo(param, result.Message));//插入错误日志
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取出错信息
    /// </summary>
    /// <param name="para"></param>
    /// <param name="errorMsg"></param>
    /// <returns></returns>
    private Dictionary<string, string> GetStartErrorInfo(AutoStartContainerParam para, string errorMsg)
    {
        return new Dictionary<string, string> { { "MfgOrderID",para.MfgOrderID},
                                                { "MfgOrderName",para.MfgOrderName},
                                                { "ProductName",para.ProductName},
                                                { "Notes",errorMsg},
                                                { "CreateEmpID",m_UserInfo.EmployeeID},
                                                { "FactoryID",m_UserInfo.FactoryID}};
    }

    /// <summary>
    /// 获取未开卡的订单数据
    /// </summary>
    /// <param name="context"></param>
    public void GetNotStartContainerOrderInfo(HttpContext context)
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("FactoryID", m_UserInfo.FactoryID);
        dic.Add("OrderName", context.Request["scanOrderName"].ToString());
        dic.Add("ProductName", context.Request["productName"].ToString());
        dic.Add("PageIndex", context.Request["pageIndex"].ToString());
        dic.Add("PageSize", context.Request["pageSize"].ToString());

        //件号主治单元
        dic.Add("factoryid", context.Request["ddlFactory"].ToString());
        dic.Add("workcenterid", context.Request["ddlWorkcenter"].ToString());
        dic.Add("teamid", context.Request["ddlTeam"].ToString());

        uMESProcessResult result = autoStartBusiness.GetNotStartContainerOrderInfo(dic, true);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 导入自动开卡规则
    /// </summary>
    /// <param name="context"></param>
    public void ImportAutoStartRule(HttpContext context)
    {
        string fpath = string.Empty;
        try
        {
            var files = context.Request.Files;
            if (files.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未上传文件！", Result = false }));
                return;
            }
            var file = files.Count > 1 ? files[files.Count - 1] : files[0];
            string IsXls = Path.GetExtension(file.FileName);
            string fileName = Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + IsXls;
            fpath = context.Server.MapPath(fileBasePath + fileName);
            file.SaveAs(fpath);//保存文件，处理完成后删除

            IWorkbook Workbook = uLMS_CommonFunction.GetWorkbookObj(fpath);
            if (Workbook == null)
            {
                DeleteFile(fpath);
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "解析文件出错", Result = false }));
                return;
            }
            DeleteFile(fpath);
            DataTable dtImport = uLMS_CommonFunction.ExcelImportToDataTable(Workbook);
            uMESProcessResult result = new uMESProcessResult() { Result = true };
            if (dtImport.Rows.Count == 0)
            {
                result.Result = false; result.Message = "解析内容出错";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            string[] strName = { "件号", "主制工区", "工艺员", "是否领料", "批次类型", "是否切断件", "分卡数", "分卡工序" };
            foreach (string str in strName)
            {
                if (!dtImport.Columns.Contains(str))
                {
                    result.Result = false; result.Message = string.Format("导入模板表头有误，缺少{0}", str);
                    break;
                }
            }
            if (!result.Result)
            {
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            if (dtImport.AsDataView().ToTable(true, "件号").Rows.Count != dtImport.Rows.Count)
            {
                result.Result = false; result.Message = "导入数据中存在相同件号的数据";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            result = SaveImportRuleData(dtImport);
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
        catch (Exception ex)
        {
            DeleteFile(fpath);//报错，则删除上传的文件
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = ex.Message, Result = false }));
        }
    }

    /// <summary>
    /// 保存导入数据
    /// </summary>
    /// <param name="drRule"></param>
    /// <returns></returns>
    private uMESProcessResult SaveImportRuleData(DataTable dtRule)
    {
        //查询工区
        DataTable dtWorkCenter = commonBusiness.GetWorkCenterByFacoryID(m_UserInfo.FactoryID, false);
        DataRow[] drs = dtWorkCenter.Select(" notes is null or notes <>'已注销' ");
        if (drs.Length > 0)
        {
            dtWorkCenter = drs.CopyToDataTable();
        }
        //查询工艺员
        DataTable dtEmployee = commonBusiness.GetEmplyeeListByRole("工艺员", m_UserInfo.FactoryID);
        //string strFactoryValue = commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "工序关联工区班组"); //获取工厂是否工序关联工区班组
        //if (strFactoryValue == "是" && !string.IsNullOrWhiteSpace(m_UserInfo.WorkCenterID))
        //{
        //    DataView dv = dtEmployee.DefaultView;
        //    dv.RowFilter = String.Format("WORKCENTERID='{0}'", m_UserInfo.WorkCenterID);
        //    dtEmployee = dv.ToTable();
        //}
        dtRule.Columns.Add("IsResult");//处理结果
        dtRule.Columns.Add("ResultMessage");
        StringBuilder srb = new StringBuilder();
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        foreach (DataRow drRule in dtRule.Rows)
        {
            srb.Clear();
            Tuple<bool, string> res = ValidImportRuleData(drRule);
            if (!res.Item1)
            {
                drRule["IsResult"] = res.Item1;
                drRule["ResultMessage"] = res.Item2;
                continue;
            }
            DataRow[] drWc = dtWorkCenter.Select(string.Format("WORKCENTERNAME = '{0}'", drRule["主制工区"].ToString()));
            if (drWc.Length == 0)
            {
                drRule["IsResult"] = false;
                drRule["ResultMessage"] = "未找到相应工区";
                continue;
            }
            DataRow[] drEm = dtEmployee.Select(string.Format("FULLNAME = '{0}'", drRule["工艺员"].ToString()));
            if (drEm.Length == 0)
            {
                drRule["IsResult"] = false;
                drRule["ResultMessage"] = "未找到相应工艺员";
                continue;
            }
            string sql = string.Format(@"SELECT ca.containerautostartruleid FROM containerAutoStartRule ca WHERE ca.Productname = '{0}' AND ca.Status = 1", drRule["件号"].ToString());
            DataTable dtR = DatabaseHelper.Query_ReturnDatTable(sql);
            AutoStartRuleParam rule = new AutoStartRuleParam()
            {
                RuleID = dtR.Rows.Count > 0 ? dtR.Rows[0]["containerautostartruleid"].ToString() : "",
                ProductName = drRule["件号"].ToString(),
                WorkCenterID = drWc[0]["WORKCENTERID"].ToString(),
                WorkCenterName = drRule["主制工区"].ToString(),
                TechnologyEmpID = drEm[0]["EMPLOYEEID"].ToString(),
                TechnologyEmpName = drRule["工艺员"].ToString(),
                IsSelfMfg = drRule["是否领料"].ToString() == "是" ? 0 : 1,
                ContainerType = GetContainerTypeByName(drRule["批次类型"].ToString()),
                ContainerTypeName = drRule["批次类型"].ToString(),
                IsCutContainer = drRule["是否切断件"].ToString() == "是" ? 1 : 0,
                CutQty = drRule["是否切断件"].ToString() == "是" ? int.Parse(drRule["分卡数"].ToString()) : 0,
                CutStartStep = drRule["件号"].ToString()
            };
            result = SaveContainerAutoStartRuleData(rule);//保存开卡规则
            drRule["IsResult"] = result.Result;
            drRule["ResultMessage"] = result.Result ? "保存成功" : result.Message;
        }
        dtRule.AcceptChanges();
        result.DBTable = dtRule;
        return result;
    }

    /// <summary>
    /// 验证导入数据
    /// </summary>
    /// <param name="drRule"></param>
    /// <returns></returns>
    private Tuple<bool, string> ValidImportRuleData(DataRow drRule)
    {
        if (string.IsNullOrWhiteSpace(drRule["件号"].ToString()))
        {
            return new Tuple<bool, string>(false, "未填写件号");
        }
        if (string.IsNullOrWhiteSpace(drRule["工艺员"].ToString()))
        {
            return new Tuple<bool, string>(false, "未填写工艺员");
        }
        if (string.IsNullOrWhiteSpace(drRule["主制工区"].ToString()))
        {
            return new Tuple<bool, string>(false, "未填写主制工区");
        }
        if (!IsVaildYesOrNo(drRule["是否领料"].ToString()))
        {
            return new Tuple<bool, string>(false, "是否领料填写有误或未填写");
        }
        if (string.IsNullOrWhiteSpace(GetContainerTypeByName(drRule["批次类型"].ToString())))
        {
            return new Tuple<bool, string>(false, "批次类型填写有误或未填写");
        }
        if (!IsVaildYesOrNo(drRule["是否切断件"].ToString()))
        {
            return new Tuple<bool, string>(false, "是否切断件填写有误或未填写");
        }
        if (drRule["是否切断件"].ToString() == "是")
        {
            if (string.IsNullOrWhiteSpace(drRule["分卡数"].ToString()))
            {
                return new Tuple<bool, string>(false, "未填写分卡数");
            }
            int cutQty = 0;
            if (!int.TryParse(drRule["分卡数"].ToString(), out cutQty))
            {
                return new Tuple<bool, string>(false, "分卡数格式错误");
            }
            if (string.IsNullOrWhiteSpace(drRule["分卡工序"].ToString()))
            {
                return new Tuple<bool, string>(false, "未填写分卡工序");
            }
        }
        string sql = string.Format("SELECT 1 FROM productbase pb WHERE pb.productname = '{0}'", drRule["件号"].ToString());
        if (DatabaseHelper.GetSingle(sql) == null)
        {
            return new Tuple<bool, string>(false, "未在系统中找到件号");
        }
        return new Tuple<bool, string>(true, "");
    }

    /// <summary>
    /// 根据批次类型名获取批次类型
    /// </summary>
    /// <param name="containerTypeName"></param>
    /// <returns></returns>
    private string GetContainerTypeByName(string containerTypeName)
    {
        string containerType = "";
        switch (containerTypeName)
        {
            case "批量加工":
                containerType = "2";
                break;
            case "单件单卡":
                containerType = "7";
                break;
            default:
                break;
        }
        return containerType;
    }

    /// <summary>
    /// 判断字符串内容'是'或'否'
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    private bool IsVaildYesOrNo(string value)
    {
        if (value == "是" || value == "否")
        {
            return true;
        }
        return false;
    }

    public enum AutoStartSaveEnum { 数据变更 = 0, 状态变更 = 1 }
    /// <summary>
    /// 保存自动开卡规则数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveContainerAutoStartRuleData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        PostFormParam pfp = JsonConvert.DeserializeObject<PostFormParam>(context.Request["params"].ToString());
        switch (pfp.RuleType)
        {
            case AutoStartSaveEnum.数据变更:
                AutoStartRuleParam autoRule = JsonConvert.DeserializeObject<AutoStartRuleParam>(pfp.Datas);
                result = ValidAndSaveAutoStartRule(autoRule);
                break;
            case AutoStartSaveEnum.状态变更:
                DataTable dtParams = JsonConvert.DeserializeObject<DataTable>(pfp.Datas);
                result = ChangeAutoStartRuleStatus(dtParams);
                break;
            default:
                break;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 更新自动开卡状态
    /// </summary>
    /// <param name="dtRule"></param>
    /// <returns></returns>
    private uMESProcessResult ChangeAutoStartRuleStatus(DataTable dtRule)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        if (dtRule.Rows.Count == 0)
        {
            result.Result = false; result.Message = "请选择数据";
            return result;
        }
        if (dtRule.AsDataView().ToTable(true, "productName").Rows.Count != dtRule.Rows.Count)
        {
            result.Result = false; result.Message = "选择了同一个件号数据";
            return result;
        }
        ArrayList sqlList = new ArrayList();
        string sql = string.Empty;
        foreach (DataRow item in dtRule.Rows)
        {
            sqlList.Add(string.Format("UPDATE containerAutoStartRule ca SET ca.status = 0 WHERE ca.productname = '{0}' AND ca.containerautostartruleid <> '{1}'", item["productName"].ToString(), item["ruleID"].ToString()));//先将除该规则的同件号的全部置为停用
            sqlList.Add(string.Format("UPDATE containerAutoStartRule ca1 SET ca1.status = decode(ca1.status,1,0,1) WHERE ca1.containerautostartruleid = '{0}'", item["ruleID"].ToString()));//再将该条数据置为另一种状态
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        result.Result = true;
        result.Message = "更改成功";
        return result;
    }
    /// <summary>
    /// 验证自动开卡规则数据
    /// </summary>
    /// <param name="autoRule"></param>
    /// <returns></returns>
    private uMESProcessResult ValidAndSaveAutoStartRule(AutoStartRuleParam autoRule)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        if (string.IsNullOrWhiteSpace(autoRule.ProductName))
        {
            result.Result = false; result.Message = "没有件号信息";
            return result;
        }
        if (string.IsNullOrWhiteSpace(autoRule.TechnologyEmpID))
        {
            result.Result = false; result.Message = "请选择工艺员";
            return result;
        }
        if (autoRule.TechnologyEmpID == autoRule.TechnologyEmpName)
        {
            result.Result = false; result.Message = "工艺员无效";
            return result;
        }
        if (string.IsNullOrWhiteSpace(autoRule.WorkCenterID))
        {
            result.Result = false; result.Message = "请选择主制工区";
            return result;
        }
        if (autoRule.IsSelfMfg == null)
        {
            result.Result = false; result.Message = "请选择是否领料";
            return result;
        }
        if (string.IsNullOrWhiteSpace(autoRule.ContainerType))
        {
            result.Result = false; result.Message = "请选择批次类型";
            return result;
        }
        if (autoRule.IsCutContainer == 1)
        {
            if (autoRule.CutQty == null || autoRule.CutQty <= 0)
            {
                result.Result = false; result.Message = "请填写分卡数量";
                return result;
            }
            if (string.IsNullOrWhiteSpace(autoRule.CutStartStep))
            {
                result.Result = false; result.Message = "请选择分卡工序";
                return result;
            }
        }
        string sql = string.Format("SELECT 1 FROM productbase pb WHERE pb.productname = '{0}'", autoRule.ProductName);
        if (DatabaseHelper.GetSingle(sql) == null)
        {
            result.Result = false; result.Message = "未在系统中找到件号";
            return result;
        }
        result = SaveContainerAutoStartRuleData(autoRule);
        return result;
    }
    /// <summary>
    /// 新增或编辑自动开卡规则
    /// </summary>
    /// <param name="autoRule"></param>
    /// <returns></returns>
    private uMESProcessResult SaveContainerAutoStartRuleData(AutoStartRuleParam autoRule)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string sql = string.Empty;//查询sql
        StringBuilder srb = new StringBuilder();//插入、更新sql
        if (string.IsNullOrWhiteSpace(autoRule.RuleID)) //如果ID为空，则添加
        {
            sql = string.Format(@"SELECT 1 FROM containerAutoStartRule ca WHERE ca.Productname = '{0}' AND ca.Status = 1", autoRule.ProductName);
            if (DatabaseHelper.GetSingle(sql) != null)
            {
                result.Result = false; result.Message = "存在已启用的相同件号";
                return result;
            }
            srb.AppendLine(@"INSERT INTO containerAutoStartRule(Containerautostartruleid,Productname,Technologyempid,Workcenterid,Isselfmfg,
                            Containertype,Status,Factoryid,Createemployeeid,Createdate,iscutcontainer,cutqty,cutstartstep) VALUES(");
            srb.AppendFormat("'{0}',", Guid.NewGuid().ToString());
            srb.AppendFormat("'{0}',", autoRule.ProductName);
            srb.AppendFormat("'{0}',", autoRule.TechnologyEmpID);
            srb.AppendFormat("'{0}',", autoRule.WorkCenterID);
            srb.AppendFormat("{0},", autoRule.IsSelfMfg);
            srb.AppendFormat("{0},", autoRule.ContainerType);
            srb.AppendLine("1,");
            srb.AppendFormat("'{0}',", m_UserInfo.FactoryID);
            srb.AppendFormat("'{0}',", m_UserInfo.EmployeeID);
            srb.AppendFormat("to_date('{0}','yyyy-mm-dd hh24:mi:ss'),", DateTime.Now.ToString());
            srb.AppendFormat("{0},", autoRule.IsCutContainer);
            if (autoRule.IsCutContainer == 1)
            {
                srb.AppendFormat("{0},", autoRule.CutQty);
                srb.AppendFormat("'{0}')", autoRule.CutStartStep);
            }
            else
            {
                srb.AppendLine("null,'')");
            }
            DatabaseHelper.ExecuteSql(srb.ToString());
        }
        else
        {
            sql = GetContainerStartRuleSql(string.Format(@" WHERE ca.Containerautostartruleid = '{0}'", autoRule.RuleID));
            DataTable dtRule = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtRule.Rows.Count == 0)
            {
                result.Result = false; result.Message = "数据过期，请重新查询";
                return result;
            }
            DataRow drRule = dtRule.Rows[0];
            StringBuilder notes = new StringBuilder();
            srb.AppendLine("UPDATE containerAutoStartRule ca SET ");
            //记录修改记录
            if (drRule["WorkCenterID"].ToString() != autoRule.WorkCenterID)//如果工作中心修改，则记录下来
            {
                notes.AppendFormat("工作中心：{0}修改为{1}，", drRule["WorkCenterName"].ToString(), autoRule.WorkCenterName);
                srb.AppendFormat("ca.workcenterid = '{0}',", autoRule.WorkCenterID);
            }
            if (drRule["TechnologyEmpID"].ToString() != autoRule.TechnologyEmpID)//如果工艺员修改，则记录下来
            {
                notes.AppendFormat("工艺员：{0}修改为{1}，", drRule["TechnologyEmpName"].ToString(), autoRule.TechnologyEmpName);
                srb.AppendFormat("ca.technologyempid = '{0}',", autoRule.TechnologyEmpID);
            }
            if (int.Parse(drRule["IsSelfMfg"].ToString()) != autoRule.IsSelfMfg)//如果是否领料修改，则记录下来
            {
                notes.AppendFormat("是否领料：{0}修改为{1}，", drRule["isselfmfgname"].ToString(), autoRule.IsSelfMfg == 1 ? "否" : "是");
                srb.AppendFormat("ca.isselfmfg = {0},", autoRule.IsSelfMfg);
            }
            if (drRule["ContainerType"].ToString() != autoRule.ContainerType)//如果批次类型修改，则记录下来
            {
                notes.AppendFormat("批次类型：{0}修改为{1}，", drRule["ContainerTypeName"].ToString(), autoRule.ContainerTypeName);
                srb.AppendFormat("ca.containertype = {0},", autoRule.ContainerType);
            }
            if (int.Parse(drRule["IsCutContainer"].ToString()) != autoRule.IsCutContainer)//如果是否切断件修改，则记录下来
            {
                notes.AppendFormat("是否切断件：{0}修改为{1}，", drRule["iscutcontainername"].ToString(), autoRule.IsCutContainer == 1 ? "是" : "否");
                srb.AppendFormat("ca.iscutcontainer = {0},", autoRule.IsCutContainer);
            }
            //更改是否切断件数值
            if (autoRule.IsCutContainer == 1)
            {
                if (drRule["cutqty"].ToString() != autoRule.CutQty.ToString()) //如果分卡数修改，则记录下来
                {
                    notes.AppendFormat("分卡数：{0}修改为{1}，", string.IsNullOrWhiteSpace(drRule["cutqty"].ToString()) ? "空值" : drRule["cutqty"].ToString(), autoRule.CutQty);
                }
                if (drRule["cutstartstep"].ToString() != autoRule.CutStartStep) //如果分卡工序修改，则记录下来
                {
                    notes.AppendFormat("分卡工序：{0}修改为{1}，", string.IsNullOrWhiteSpace(drRule["cutstartstep"].ToString()) ? "空值" : drRule["cutstartstep"].ToString(), autoRule.CutStartStep);
                }
                srb.AppendFormat("ca.cutqty = {0},", autoRule.CutQty);
                srb.AppendFormat("ca.cutstartstep = '{0}'", autoRule.CutStartStep);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(drRule["cutqty"].ToString())) //如果分卡数修改，则记录下来
                {
                    notes.AppendFormat("分卡数：{0}修改为空值，", drRule["cutqty"].ToString());
                }
                if (!string.IsNullOrWhiteSpace(drRule["cutstartstep"].ToString())) //如果分卡工序修改，则记录下来
                {
                    notes.AppendFormat("分卡工序：{0}修改为空值", drRule["cutstartstep"].ToString());
                }
                srb.AppendFormat("ca.cutqty = null,ca.cutstartstep = ''");
            }
            srb.AppendFormat(" WHERE ca.Containerautostartruleid = '{0}'", autoRule.RuleID);

            ArrayList sqlList = new ArrayList();
            sqlList.Add(srb.ToString());
            //如果修改内容不为空
            if (notes.Length > 0)
            {
                //插入修改日志
                sqlList.Add(commonBusiness.GetInsertCommonMethodOperaLogSql(autoRule.RuleID, m_UserInfo.EmployeeID, notes.ToString().TrimEnd('，'), ruleOperaType));
            }
            DatabaseHelper.ExecuteSqlTran(sqlList);//统一提交
        }
        result.Message = "保存成功";
        return result;
    }

    /// <summary>
    /// 获取自动开卡规则维护数据
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerStartRuleData(HttpContext context)
    {
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(" WHERE ca.factoryid = '{0}'", m_UserInfo.FactoryID);
        //查询件号
        if (!string.IsNullOrWhiteSpace(context.Request["productName"].ToString()))
        {
            sql.AppendFormat(" AND pb.productname like '%{0}%'", context.Request["productName"].ToString());
        }
        //查询创建人
        if (!string.IsNullOrWhiteSpace(context.Request["createName"].ToString()))
        {
            sql.AppendFormat(" AND (e1.fullname LIKE '%{0}%' OR e1.employeename = '{0}')", context.Request["createName"].ToString());
        }
        //查询工区
        if (!string.IsNullOrWhiteSpace(context.Request["workCenter"].ToString()))
        {
            sql.AppendFormat(" AND wc.workcenterid = '{0}'", context.Request["workCenter"].ToString());
        }
        //查询工艺员
        if (!string.IsNullOrWhiteSpace(context.Request["technologyName"].ToString()))
        {
            sql.AppendFormat(" AND (e.fullname LIKE '%{0}%' OR e.employeename = '{0}')", context.Request["technologyName"].ToString());
        }
        //查询是否领料
        if (!string.IsNullOrWhiteSpace(context.Request["isSelfMfg"].ToString()))
        {
            sql.AppendFormat(" AND ca.isselfmfg = {0}", context.Request["isSelfMfg"].ToString());
        }
        //查询状态
        if (!string.IsNullOrWhiteSpace(context.Request["status"].ToString()))
        {
            sql.AppendFormat(" AND ca.status = {0}", context.Request["status"].ToString());
        }
        //查询是否切断件
        if (!string.IsNullOrWhiteSpace(context.Request["isCutContainer"].ToString()))
        {
            sql.AppendFormat(" AND ca.iscutcontainer = {0}", context.Request["isCutContainer"].ToString());
        }
        //件号主制单元
        if (!string.IsNullOrWhiteSpace(context.Request["ddlProductTeam"].ToString()))
        {
            sql.AppendFormat(" AND tm.teamid = '{0}'", context.Request["ddlProductTeam"].ToString());
        }
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(context.Request["pageIndex"].ToString());
        pageDto.PageSize = int.Parse(context.Request["pageSize"].ToString());
        pageDto.strSQL = GetContainerStartRuleSql(sql.ToString());
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取自动开卡规则明细
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerStartRuleDetailInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(GetContainerStartRuleSql(string.Format(" WHERE ca.productname = '{0}' AND ca.status = 1", context.Request["productName"].ToString())));
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取件号默认信息以及工艺默认信息
    /// </summary>
    /// <param name="context"></param>
    public void GetProductAndWorkFlowInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string productName = context.Request["productName"].ToString();
        string sql = string.Format(@"SELECT 1 FROM containerAutoStartRule ca WHERE ca.Productname = '{0}' AND ca.Status = 1", productName);
        if (DatabaseHelper.GetSingle(sql) != null)
        {
            result.Result = false; result.Message = "存在已启用的相同件号";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        sql = string.Format(@"SELECT pb.productname,p.description,p.productrevision,p.workflowbaseid,wb1.workflowname,w.workflowrevision,w.workflowid
                        FROM productbase pb 
                        LEFT JOIN product p ON p.productid = pb.revofrcdid
                        LEFT JOIN Workflowbase wb ON wb.workflowbaseid = p.workflowbaseid
                        LEFT JOIN Workflow w ON w.workflowid = NVL(wb.revofrcdid,p.workflowid)
                        LEFT JOIN Workflowbase wb1 ON wb1.workflowbaseid = w.workflowbaseid
                        WHERE pb.productname = '{0}'", context.Request["productName"].ToString());

        DataTable dtProductWorkflow = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtProductWorkflow.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "未查询到件号数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //查询工序
        sql = string.Format(@"SELECT ws.workflowstepid,ws.workflowstepname FROM workflowstep ws WHERE ws.workflowid = '{0}' ORDER BY ws.sequence", dtProductWorkflow.Rows[0]["workflowid"].ToString());
        DataTable dtStep = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtStep.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "未查询到工艺数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        dtProductWorkflow.TableName = "dtProductWorkflow";
        result.DBDataSet.Tables.Add(dtProductWorkflow);
        dtStep.TableName = "dtStep";
        result.DBDataSet.Tables.Add(dtStep);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 初始化自动开卡规则编辑页面数据
    /// </summary>
    /// <param name="context"></param>
    public void InitAutoStartRuleDialogData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        //查询工区
        DataTable dtWorkCenter = commonBusiness.GetWorkCenterByFacoryID(m_UserInfo.FactoryID, false);
        DataRow[] drs = dtWorkCenter.Select(" notes is null or notes <>'已注销' ");
        if (drs.Length > 0)
        {
            dtWorkCenter = drs.CopyToDataTable();
        }
        dtWorkCenter.TableName = "dtWorkCenter";
        result.DBDataSet.Tables.Add(dtWorkCenter);
        //查询工艺员
        DataTable dtEmployee = commonBusiness.GetEmplyeeListByRole("工艺员", m_UserInfo.FactoryID);
        string strFactoryValue = commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "工序关联工区班组"); //获取工厂是否工序关联工区班组
        if (strFactoryValue == "是" && !string.IsNullOrWhiteSpace(m_UserInfo.WorkCenterID))
        {
            DataView dv = dtEmployee.DefaultView;
            dv.RowFilter = String.Format("WORKCENTERID='{0}'", m_UserInfo.WorkCenterID);
            dtEmployee = dv.ToTable();
        }
        dtEmployee.TableName = "dtEmployee";
        result.DBDataSet.Tables.Add(dtEmployee);
        //查询规则数据
        if (!string.IsNullOrWhiteSpace(context.Request["ruleID"].ToString()))
        {
            DataTable dtRule = DatabaseHelper.Query_ReturnDatTable(GetContainerStartRuleSql(string.Format(" WHERE ca.containerautostartruleid = '{0}'", context.Request["ruleID"].ToString())));
            dtRule.TableName = "dtRule";
            result.DBDataSet.Tables.Add(dtRule);
            //查询工序
            string sql = string.Format(@"SELECT ws.workflowstepid,ws.workflowstepname FROM workflowstep ws WHERE ws.workflowid = '{0}' ORDER BY ws.sequence", dtRule.Rows[0]["workflowid"].ToString());
            DataTable dtStep = DatabaseHelper.Query_ReturnDatTable(sql);
            dtStep.TableName = "dtStep";
            result.DBDataSet.Tables.Add(dtStep);
            if (dtStep.Select(string.Format("workflowstepname='{0}'", dtRule.Rows[0]["cutstartstep"].ToString())).Length == 0)
            {
                dtRule.Rows[0]["cutstartstep"] = "";//如果最新版工艺下的工序不包含该分卡工序，则清空
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取自动开卡规则SQL
    /// </summary>
    /// <param name="sqlWhere"></param>
    /// <returns></returns>
    public string GetContainerStartRuleSql(string sqlWhere)
    {
        return @"SELECT pb.productname,p.description,p.productrevision,wb1.workflowname,w.workflowrevision,ca.iscutcontainer,ca.cutqty,ca.cutstartstep,
                        ca.technologyempid,ca.status,ca.containerautostartruleid,wb1.workflowname ||':' || w.workflowrevision workflowinfo,w.workflowid,
                        ca.workcenterid,wc.workcentername,e.fullname technologyempName,e1.fullname createname,ca.isselfmfg,ca.containertype,ca.createdate,
                        DECODE(ca.isselfmfg,0,'是','否') isselfmfgname,DECODE(ca.containertype,2,'批量加工',3,'批量带子序号',7,'单件单卡','') containertypename,
                        DECODE(ca.iscutcontainer,1,'是','否') iscutcontainername,tm.teamname productteamname
                        FROM containerAutoStartRule ca
                        LEFT JOIN productbase pb ON pb.productname = ca.productname
                        LEFT JOIN product p ON p.productid = pb.revofrcdid
                        LEFT JOIN Workflowbase wb ON wb.workflowbaseid = p.workflowbaseid
                        LEFT JOIN Workflow w ON w.workflowid = NVL(wb.revofrcdid,p.workflowid)
                        LEFT JOIN Workflowbase wb1 ON wb1.workflowbaseid = w.workflowbaseid
                        LEFT JOIN Workcenter wc ON wc.workcenterid = ca.workcenterid
                        LEFT JOIN employee e ON e.employeeid = ca.technologyempid
                        LEFT JOIN productteaminfo pti ON pti.productname = ca.productname AND pti.isuse = 0
                        LEFT JOIN team tm ON tm.teamid = pti.teamid
                        LEFT JOIN employee e1 ON e1.employeeid = ca.createemployeeid " + sqlWhere;
    }


    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="fpath">文件地址</param>
    private void DeleteFile(string fpath)
    {
        if (File.Exists(fpath))
        {
            new FileInfo(fpath).Attributes = FileAttributes.Normal;
            File.Delete(fpath);
        }
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    public class PostFormParam
    {
        /// <summary>
        /// 保存类型
        /// </summary>
        public AutoStartSaveEnum RuleType { get; set; }
        /// <summary>
        /// 对象数据
        /// </summary>
        public string Datas { get; set; }

    }

    /// <summary>
    /// 自动开卡规则参数
    /// </summary>
    public class AutoStartRuleParam
    {
        /// <summary>
        /// 主ID
        /// </summary>
        public string RuleID { get; set; }
        /// <summary>
        /// 件号
        /// </summary>
        public string ProductName { get; set; }
        /// <summary>
        /// 工区ID
        /// </summary>
        public string WorkCenterID { get; set; }
        /// <summary>
        /// 工区名
        /// </summary>
        public string WorkCenterName { get; set; }
        /// <summary>
        /// 工艺员ID
        /// </summary>
        public string TechnologyEmpID { get; set; }
        /// <summary>
        /// 工艺员名
        /// </summary>
        public string TechnologyEmpName { get; set; }
        /// <summary>
        /// 批次类型
        /// </summary>
        public string ContainerType { get; set; }
        /// <summary>
        /// 批次类型名
        /// </summary>
        public string ContainerTypeName { get; set; }
        /// <summary>
        /// 是否领料
        /// </summary>
        public int IsSelfMfg { get; set; }
        /// <summary>
        /// 是否切断件
        /// </summary>
        public int IsCutContainer { get; set; }
        /// <summary>
        /// 分卡数
        /// </summary>
        public int? CutQty { get; set; }
        /// <summary>
        /// 分卡工序
        /// </summary>
        public string CutStartStep { get; set; }
        /// <summary>
        /// 分卡工序名
        /// </summary>
        public string CutStartStepName { get; set; }
    }
}